import taosrest

def list_tables(database_name):
    try:
        conn = taosrest.connect(
            url="http://192.168.1.251:6041",
            user="root",
            password="taosdata"
        )
        cursor = conn.cursor()
        # 查询指定数据库中的所有表
        cursor.execute(f"SELECT name FROM information_schema.ins_tables WHERE db_name = '{database_name}'")
        tables = cursor.fetchall()
        print(f"📁 数据库 {database_name} 中的表：")
        for table in tables:
            print(f"  - {table[0]}")
    except Exception as e:
        print(f"❌ 查询失败: {e}")
    finally:
        if 'conn' in locals():
            conn.close()

def show_all_databases():
    try:
        conn = taosrest.connect(
            url="http://192.168.1.251:6041",
            user="root",
            password="taosdata"
        )
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM information_schema.ins_databases")
        result = cursor.fetchall()
        print("📄 当前数据库列表：")
        for row in result:
            print(f"  - {row[0]}")
    except Exception as e:
        print("❌ 查询失败:", e)
    finally:
        if 'conn' in locals():
            conn.close()

def describe_table(database_name, table_name):
    try:
        conn = taosrest.connect(
            url="http://192.168.1.251:6041",
            user="root",
            password="taosdata"
        )
        cursor = conn.cursor()
        # 查询子表的结构信息
        cursor.execute(f"DESCRIBE {database_name}.{table_name}")
        columns = cursor.fetchall()
        print(f"📐 表 {table_name} 的结构：")
        print(f"{'字段名':<20}{'类型':<15}{'长度':<10}{'备注':<10}")
        for col in columns:
            field = col[0]
            dtype = col[1]
            length = col[2]
            note = col[3] if len(col) > 3 else ''
            print(f"{field:<20}{dtype:<15}{length:<10}{note:<10}")
    except Exception as e:
        print(f"❌ 查询失败: {e}")
    finally:
        if 'conn' in locals():
            conn.close()

def query_table_data(database_name, table_name, limit=10):
    try:
        conn = taosrest.connect(
            url="http://192.168.1.251:6041",
            user="root",
            password="taosdata"
        )
        cursor = conn.cursor()
        # 查询子表的数据
        cursor.execute(f"SELECT * FROM {database_name}.{table_name} LIMIT {limit}")
        rows = cursor.fetchall()
        print(f"📄 表 {table_name} 的前 {limit} 条记录：")
        for row in rows:
            print(row)
    except Exception as e:
        print(f"❌ 查询失败: {e}")
    finally:
        if 'conn' in locals():
            conn.close()

#             执行普通sal的函数





# 调用函数
# show_all_databases()
# list_tables("syslogdb")
# describe_table("syslogdb", "syslog_logs_192_168_1_254")
# query_table_data("syslogdb", "syslog_logs_192_168_1_254", limit=10)
